﻿using MuXue.Zyiz.Template.Common;
using MuXue.Zyiz.Template.Domain.Model;
using MuXue.Zyiz.Template.OuterClient.MsgClient;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
 

namespace MuXue.Zyiz.Template.OuterClient
{
    /// <summary>
    /// 消息发送客户端
    /// </summary>
    public interface IMsgApiClient
    {

        /// <summary>
        /// 调用张炅的接口：向SD发送消息
        /// </summary>
        /// <param name="hrcodeStr">hrcode，多个以|隔开</param>
        /// <param name="msg">消息内容</param>
        /// <returns></returns>
        Task<Result<string>> SendWxWorkMsgAsync(string hrcodeStr, string msg);

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        Task<Result<string>> HealthCheck();
    }

    public   class MsgApiClient: IMsgApiClient
    {

        private readonly JsonSerializerSettings _serializerSettings;
        private readonly MsgClientConfiguration _config;
        private readonly HttpClient _client;
        private ILogger _logger;
        public MsgApiClient(IServiceProvider provider, HttpClient client, ILogger<MsgApiClient> logger)
        {
            
            _config = provider.GetRequiredService<IOptions<MsgClientConfiguration>>().Value;
            _client = client;
           // _client.BaseAddress = new Uri(_config.url);
            _logger = logger;
        }

        /// <summary>
        /// 调用张炅的接口：向SD发送消息
        /// </summary>
        /// <param name="hrcodeStr">hrcode，多个以|隔开</param>
        /// <param name="msg">消息内容</param>
        /// <returns></returns>
        public async Task<Result<string>> SendWxWorkMsgAsync(string hrcodeStr, string msg)
        {
            Result<string> result = new Result<string>();
            string funName = "【post:调用张炅微信企业消息推送接口】";
            try
            { 
                //1先jwt登陆 
                string account = _config.jwt_account; //账号
                string password = _config.jwt_password;//密码
                MsgApiResult<TokenResp> tokenRet = await ZyizHttpClientExtensions.PostData<MsgApiResult<TokenResp>>(_client, _logger,"/api/Auth/GetToken", new { account, password });

                if (tokenRet == null || tokenRet.Return_code != "0000" || tokenRet.Return_data == null || string.IsNullOrWhiteSpace(tokenRet.Return_data.token))
                {
                    //发出警告
                    _logger.LogError($"{funName}jwt获取账号失败。请管理员紧急处理！！！");
                    result.state = false;
                    result.error_code = ErrorCode.OuterApiError;
                    result.error_msg = $"{funName}jwt获取账号失败。请管理员紧急处理！！！";
                    return result;
                }
                //2发送
                string token = tokenRet.Return_data.token;

                WeiXinWorkMessageReq msgReq = new WeiXinWorkMessageReq(hrcodeStr, msg);

                MsgApiResult<WeiXinWorkMessageResponse> sendRet = await ZyizHttpClientExtensions.PostData<MsgApiResult<WeiXinWorkMessageResponse>>(_client, _logger, "/api/weixin/work/messages/send", msgReq);

                if (sendRet != null && sendRet.Return_code == "0000" && sendRet.Return_data != null && !string.IsNullOrWhiteSpace(sendRet.Return_data.MessageId))
                {
                    _logger.LogInformation($"{funName},向sd：{hrcodeStr}推送消息成功");
                    result.state = true;
                    result.data = sendRet.Return_data.MessageId;
                }
                else
                {
                    result.state = false;
                    result.error_msg = sendRet.Return_msg;
                    _logger.LogError($"{funName},向sd：{hrcodeStr}推送消息失败：{sendRet.Return_msg}");
                }

            }
            catch (Exception ex)
            {
                result.state = false;
                result.error_code = ErrorCode.OuterApiError;
                result.error_msg = funName + "调用外部接口异常：。" + ex.Message;
                _logger.LogError(ex, $"{funName}向{hrcodeStr}推送消息处理异常：{ex.Message}");
            }


            return result;

        }


        public async Task<Result<string>> HealthCheck()
        {
            Result<string> result = new Result<string>();
            string funName = "【msg检查检查】";
            try
            {
                //1先jwt登陆 
                string account = _config.jwt_account; //账号
                string password = _config.jwt_password;//密码
                MsgApiResult<TokenResp> tokenRet = await ZyizHttpClientExtensions.PostData<MsgApiResult<TokenResp>>(_client, _logger, "/api/Auth/GetToken", new { account, password });

                if (tokenRet == null || tokenRet.Return_code != "0000" || tokenRet.Return_data == null || string.IsNullOrWhiteSpace(tokenRet.Return_data.token))
                {
                    //发出警告
                    _logger.LogError($"{funName}jwt获取账号失败。请管理员紧急处理！！！");
                    result.state = false;
                    result.error_code = ErrorCode.OuterApiError;
                    result.error_msg = $"{funName}jwt获取账号失败。请管理员紧急处理！！！";
                    return result;
                }

                //2发送
                string token = tokenRet.Return_data.token;
                _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
                var request = new HttpRequestMessage(HttpMethod.Get, "/api/Default/HealthCheck");
                var response = await _client.SendAsync(request);

                if (response.IsSuccessStatusCode)
                {
                    string respStr = response.Content.ReadAsStringAsync().Result;
                    result.data = respStr;
                    result.state = true;
                }
                else
                {
                   
                }

            }
            catch (Exception ex)
            {
                result.state = false;
                result.error_code = ErrorCode.OuterApiError;
                result.error_msg = funName + "调用外部接口异常：。" + ex.Message;
                _logger.LogError(ex, $"{funName}处理异常：{ex.Message}");
            }


            return result;
        }


        /// <summary>
        /// 获取jwt的token
        /// </summary>
        /// <returns></returns>
        public async Task<Result<string>> GetJwtToken()
        {
            Result<string> result = new Result<string>();
            string funName = "【Msg获取jwt的token】";
            try
            {
                //1先jwt登陆 
                string account = _config.jwt_account; //账号
                string password = _config.jwt_password;//密码
                MsgApiResult<TokenResp> tokenRet = await ZyizHttpClientExtensions.PostData<MsgApiResult<TokenResp>>(_client, _logger, "/api/Auth/GetToken", new { account, password });

                if (tokenRet == null || tokenRet.Return_code != "0000" || tokenRet.Return_data == null || string.IsNullOrWhiteSpace(tokenRet.Return_data.token))
                {
                    //发出警告
                    _logger.LogError($"{funName}jwt获取账号失败。请管理员紧急处理！！！");
                    result.state = false;
                    result.error_code = ErrorCode.OuterApiError;
                    result.error_msg = $"{funName}jwt获取账号失败。请管理员紧急处理！！！";
                    return result;
                }

                
                string token = tokenRet.Return_data.token;
                result.state = true;
                result.data = token;

            }
            catch (Exception ex)
            {
                result.state = false;
                result.error_code = ErrorCode.OuterApiError;
                result.error_msg = $"{funName}处理异常：{ex.Message}";
                _logger.LogError(ex, $"{funName}处理异常：{ex.Message}");
            }


            return result;

        }
    }
}
